package com.getword.security;

import com.getword.security.core.properties.SecurityProperties;
import com.getword.security.core.validate.code.ValidateCodeFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

//import javax.sql.DataSource;


@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private SecurityProperties securityProperties;


    //注入自定义的登录成功处理器
    @Autowired
    private AuthenticationSuccessHandler vstudyAuthenticationSuccessHandler;

    //注入自定义的登录失败处理器
    @Autowired
    private AuthenticationFailureHandler vstudyAuthenticationFailHandler;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 从数据库中查找到token后，需要根据用户名查找用户密码
    @Autowired
    private UserDetailsService myUserDetailsService;

//    @Autowired
//    private DataSource dataSource;

//    @Bean
//    public PersistentTokenRepository persistentTokenRepository() {
//        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
//        tokenRepository.setDataSource(dataSource);
////        tokenRepository.setCreateTableOnStartup(true);
//        return tokenRepository;
//    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
        auth.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.userDetailsService(myUserDetailsService);
//        http.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncoder());

        // 在过滤器链上加入自定义过滤器
        ValidateCodeFilter codeFilter = new ValidateCodeFilter();
        // 设置过滤器异常处理器
        codeFilter.setAuthenticationFailureHandler(vstudyAuthenticationFailHandler);
        codeFilter.setSecurityProperties(securityProperties);
        codeFilter.afterPropertiesSet();
        http.addFilterBefore(codeFilter, UsernamePasswordAuthenticationFilter.class)
                .formLogin()// 表单登录
                .loginPage("/authentication/require") //将登录页面重定向到controller
                .loginProcessingUrl("/authentication/form")
                .successHandler(vstudyAuthenticationSuccessHandler)
                .failureHandler(vstudyAuthenticationFailHandler)
                .and()
                .headers().frameOptions().disable()
            .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login.html")
                .invalidateHttpSession(true)
            .and()
//                .rememberMe()
//                .tokenRepository(persistentTokenRepository())
//                .tokenValiditySeconds(securityProperties.getBrowser().getRememberMeSecond()) //记住我
//                .userDetailsService(myUserDetailsService)
//                .and()
                .authorizeRequests() //请求授权
                .antMatchers("/authentication/require","/upload/**",
                        "/code/image", "/css/**","/api/**", "/js/**", "/images/*", "/",
                        securityProperties.getBrowser().getLoginPage())
                .permitAll()//该页面允许通过
                .antMatchers("/student/**").hasRole("student")
                .antMatchers("/teacher/**").hasRole("teacher")
                .antMatchers("/admin/**").hasRole("admin")
//                .antMatchers("/api/**").authenticated()
                .anyRequest().authenticated()  // 其他资源需要认证
            .and()
                .csrf().disable();  // 将跨站防护关掉
        System.out.println("认证权限配置完成.....");
    }

}
